#' ---
#' author: "```matthew.pietryka@gmail.com```"
#' date: "2019-07-26"
#' output:
#'  html_document:
#'    warning: false
#'    toc: true
#'    code_folding: hide
#' ---


#' **PURPOSE:**
#' This script creates plots to display the relationship between time and text similarity (Figure 3)"




# GET STARTED ---------------

#  load packages
library(tidyverse)


#  load data and plotting preferences
source("SC-Plots-Load-the-Data.R")
source("SC-Plots-Preferences.R")



# SCATTER PLOT ---------------------

df_plot <- df_new  %>%
  mutate(same_state_lab = recode(share_border,
                                 `1` = "Same-state dyad",
                                 `0` = "Different states"))


scatter_plot <- ggplot(df_plot,
                       aes(x = time_diff/365, y = ratio,
                           color = same_state_lab,
                           alpha = same_state_lab)) +
  geom_point(size = 3) +
  theme_sc(axis_title_size = 12, base_size = 12) +
  scale_color_manual(values = c("grey70", "#0072B2")) +
  scale_alpha_manual(values = c(.3, .8), guide = FALSE) +
  ggtitle(NULL) +
  xlab("Years between ratification") +
  ylab("Proportion borrowed") +
  theme(
    axis.text = element_text(size = rel(.9)),
    panel.grid.minor = element_blank(),
    panel.grid.major.x = element_blank(),
    legend.position = c(0.7, 0.95),
    legend.margin = margin(t = 0, b = 0, unit = 'cm'),
    legend.background = element_rect(fill = "gray95", color = NA),
    legend.title = element_blank(),
    legend.direction  = "vertical",
    legend.text = element_text(size = rel(1.0))
  ) +
  guides(color = guide_legend(reverse = TRUE))


graphics.off()
windows(4, 4)
scatter_plot





# SMOOTHED LINE PLOT ---------------------
smooth_plot <- df_new  %>%
  ggplot(aes(x = time_diff/365, y = ratio)) +
  geom_smooth(color = "grey30", size = 1.5, method = "loess") +
  theme_sc(axis_title_size = 12, base_size = 12) +
  scale_y_continuous(breaks = seq(0, .008, .004)) +
  ggtitle(NULL) +
  xlab("Years between ratification") +
  ylab("Proportion borrowed") +
  theme(
    axis.text = element_text(size = rel(.9)),
    panel.grid.minor = element_blank(),
    legend.position = "top",
    legend.title = element_blank()
    )

windows(4, 4)
smooth_plot




# SAVE ---------------

graphics.off()
windows(4, 4)
scatter_plot
ggsave("Plots/time_scatter.png")

graphics.off()
windows(4, 4)
smooth_plot
ggsave("Plots/time_smooth.png")

